package chapter03

/**
 * @program lu-scala01
 * @description: 单例模式
 * @author: zhanglu
 * @create: 2022-03-20 21:38:00
 */
object C12_Singleton {

  def main(args: Array[String]): Unit = {
    val student1 = Student12.getInstance
    student1.printInfo()

    val student2 = Student12.getInstance
    student2.printInfo()

    println(student1)
    println(student2)
    println(student1 == student2)
  }

}

class Student12 private(val name: String, val age: Int) {

  def printInfo() {
    println(s"student name $name age $age sex ${Student11.sex}")
  }

}

/**
 * 饿汉式
 */
//object Student12{
//  private val student: Student12 = new Student12("lu", 18)
//  def getInstance = student
//}

/**
 * 懒汉式
 */
object Student12{
  private var student: Student12 = _
  def getInstance: Student12 ={
    if(student == null){
      //没有对象实例，则创建一个
      student = new Student12("lu", 18)
    }
    student
  }
}

